// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({    env: "dzc-aapp-0g1mx02g41e97626", }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  const { favoriteId, isFavorited, targetId, userId } = event
  const db = cloud.database()
  const _ = db.command

  // 取消收藏
  if (isFavorited) {
    await db.collection('favorites').doc(favoriteId).remove()
    await db.collection('users').doc(targetId).update({
      data: { favorites: _.inc(-1) }
    })
    return { success: true }
  }
  exports.main = async (event) => {
    const { targetId, userId, isFavorited, targetInfo } = event;
    const db = cloud.database();
    const _ = db.command;
    if (isFavorited) {
      // 取消收藏
      await Promise.all([
        db.collection('favorites').where({
          userId,
          targetId
        }).remove(),
        db.collection('users').doc(targetId).update({
          data: { favoritesCount: _.inc(-1) }
        })
      ]);
    } else {
      // 新增收藏
      await Promise.all([
        db.collection('favorites').add({
          data: {
            userId,
            targetId,
            targetInfo, // 存储用户信息快照
            createdAt: db.serverDate()
          }
        }),
        db.collection('users').doc(targetId).update({
          data: { favoritesCount: _.inc(1) }
        })
      ]);
    }
    return { success: true };
  }
}